package handler

import (
	"car-auth-backend/cache"
	"car-auth-backend/model"
	"encoding/json"
	"github.com/gin-gonic/gin"
	"strconv"
	"time"
)

func RepoAdd(c *gin.Context) {
	repo_name := c.PostForm("repo_name")
	repo_code := c.PostForm("repo_code")
	if repo_name == "" || repo_code == "" {
		c.JSON(200, gin.H{
			"code": 500,
			"msg":  "字段不能为空",
		})
		return
	}
	data := model.Repo{
		RepoName: repo_name,
		RepCode:  repo_code,
	}
	err := model.DB.Debug().Create(&data).Error
	if err != nil {
		c.JSON(200, gin.H{
			"code": 500,
			"msg":  "添加失败",
		})
		return
	}
	c.JSON(200, gin.H{
		"code": 200,
		"msg":  "添加成功",
	})
	return
}
func RepoList(c *gin.Context) {
	/*
		SELECT
			  repo_orders.id AS OrderId,
			  repo_orders.order_code AS OrderCode,
			  repo_orders.good_num AS GoodNum,
			  repo_orders.order_price AS OrderPrice,
			  repos.rep_code AS RepCode,
			  repos.repo_name AS RepoName
			FROM
			  repo_orders
			  LEFT JOIN repos ON repos.id = repo_orders.rep_id
	*/
	page, _ := strconv.Atoi(c.DefaultQuery("page", "1"))
	size, _ := strconv.Atoi(c.DefaultQuery("size", "10"))
	offset := (page - 1) * size
	var repoOrderList []model.RepoOrderList
	redis_key := "repo_order_list_page" + strconv.Itoa(page)
	cacheData, _ := cache.Rdb.Get(cache.Ctx, redis_key).Result()
	if cacheData == "" {
		model.DB.Table("repo_orders").
			Select(
				"repo_orders.id AS OrderId",
				"repo_orders.order_code AS OrderCode",
				"repo_orders.good_num AS GoodNum",
				"repo_orders.order_price AS OrderPrice",
				"repos.rep_code AS RepCode",
				"repos.repo_name AS RepoName",
			).
			Joins("LEFT JOIN repos ON repos.id = repo_orders.rep_id").
			Offset(offset).
			Limit(size).
			Debug().
			Find(&repoOrderList)
		jsonData, _ := json.Marshal(&repoOrderList)
		cache.Rdb.Set(cache.Ctx, redis_key, jsonData, time.Hour*2)
	} else {
		json.Unmarshal([]byte(cacheData), &repoOrderList)
	}
	var total int64
	model.DB.Table("repo_orders").Count(&total)
	c.JSON(200, gin.H{
		"code":  200,
		"msg":   "ok",
		"data":  repoOrderList,
		"total": total,
	})
	return
}
